package com.leantech.android.browser

import android.app.Application
import android.content.res.Configuration
import com.cscj.android.repository.settings.Settings
import com.cscj.android.repository.settings.model.SettingConstants
import com.cscj.android.utils.LOG
import com.leantech.android.browser.skin.SkinManager
import com.leantech.android.browser.utils.CrashHandler
import com.qmuiteam.qmui.arch.QMUISwipeBackActivityManager
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject

class AppInitial : KoinComponent {

    companion object {
        const val SkinDark = 1
    }

    private val settings by inject<Settings>()
    private val appScope by inject<CoroutineScope>()
    private val adInitial by inject<AdInitial>()

    private val crashHandler by inject<CrashHandler>()
    private val browserSetting by inject<Settings.BrowserSetting>()

    fun init(app: Application) {
        crashHandler.init()

        initQMUI(app)
        appScope.launch {
            settings.init()
        }
        adInitial.init(app)

        initSkinManager(app)
    }

    private fun initQMUI(app: Application) {
        QMUISwipeBackActivityManager.init(app)
    }

    private fun initSkinManager(app: Application){
        SkinManager.install(app.applicationContext)
        appScope.launch {
            browserSetting.darkModeFlow().collectLatest { darkMode ->
                LOG.d("AppInitial", "SkinManager darkMode change to $darkMode")
                when(darkMode){
                    SettingConstants.DarkModeForceDark -> SkinManager.changeSkin(app.applicationContext, SkinManager.SkinDark)
                    SettingConstants.DarkModeDisabled -> SkinManager.changeSkin(app.applicationContext, SkinManager.SkinDefault)
                    SettingConstants.DarkModeFollowSystem -> {
                        when (app.applicationContext.resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK) {
                            Configuration.UI_MODE_NIGHT_YES -> {
                                SkinManager.changeSkin(app.applicationContext, SkinManager.SkinDark)
                            }
                            else -> {
                                SkinManager.changeSkin(app.applicationContext, SkinManager.SkinDefault)
                            }
                        }
                    }
                }
            }
        }
    }

}